package com.jintu.portal.pojo.entity.mongo;

import com.alibaba.fastjson.JSONObject;
import com.jintu.portal.config.Constant;
import com.jintu.portal.pojo.fingerprint.FingerRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.text.SimpleDateFormat;
import java.util.UUID;

/**
 * @author very
 */
@Slf4j
@Data
@Document(collection = Constant.DEVICE_FINGER_PRINT_COLLECTION)
public class DeviceFinger {

    public static final ThreadLocal<SimpleDateFormat> sdf = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    @Id
    private String id;

    @Field("uniqueId")
    private String uniqueId;

    @Field("lastTimestamp")
    private Long lastTimestamp;

    @Field("orderId")
    private String orderId;

    @Field("merchCode")
    private String merchCode;

    @Field("tranTime")
    private String tranTime;

    @Field("updateTranTimeStamp")
    private Long updateTranTimeStamp;

    @Field("tranTimestamp")
    private Long tranTimestamp;

    @Field("stepId")
    private String stepId;

    @Field("sign")
    private String sign;

    @Field("data")
    private JSONObject data;

    public static DeviceFinger convertByRequestBody(FingerRequest request){
        DeviceFinger deviceFinger = new DeviceFinger();
        deviceFinger.setData(request.getData());
        deviceFinger.setOrderId(request.getOrderId());
        deviceFinger.setMerchCode(request.getMerchCode());
        deviceFinger.setTranTime(request.getTranTime());
        Long transTimestamp = 0L;
        try {
            transTimestamp = sdf.get().parse(request.getTranTime()).getTime();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        deviceFinger.setUpdateTranTimeStamp(transTimestamp);
        deviceFinger.setTranTimestamp(System.currentTimeMillis());
        deviceFinger.setSign(request.getSign());
        deviceFinger.setLastTimestamp(System.currentTimeMillis());
        deviceFinger.setId(generateMongoId());
        deviceFinger.setUniqueId(generateDeviceId(request));
        return deviceFinger;
    }

    private static String generateDeviceId(FingerRequest request){
        JSONObject data = request.getData();
        if(data == null || data.isEmpty()){
            return null;
        }
        String imei = data.getString("imei");
        String imsi = data.getString("imsi");
        String wifiMac = data.getString("curWifiMac");
        String userAgent = data.getString("userAgent");
        return DigestUtils.md5Hex(imei + imsi + wifiMac + userAgent);
    }

    private static String generateMongoId(){
        return DigestUtils.md5Hex(UUID.randomUUID().toString() + System.nanoTime());
    }
}
